// 个人资料编辑模块
import { showSuccessModal, showEmailCheckModal } from './notification-manager.js';

// 使用全局函数（由 core.js 提供）
const { getUserInfo, setUserInfo, validateEmail } = window;

/**
 * 初始化编辑资料模态框
 */
export function initializeEditProfileModal() {
    const editProfileBtn = document.getElementById('edit-profile-btn');
    const closeModalBtn = document.getElementById('close-edit-modal');
    const editProfileModal = document.getElementById('edit-profile-modal');
    const editProfileForm = document.getElementById('edit-profile-form');
    
    if (!editProfileBtn || !closeModalBtn || !editProfileModal || !editProfileForm) return;
    
    // 显示编辑资料模态框
    editProfileBtn.addEventListener('click', function() {
        // 填充现有用户信息到表单
        const user = getUserInfo();
        if (user) {
            document.getElementById('edit-username').value = user.username || '';
            document.getElementById('edit-user-title').value = user.nickname || '';
            document.getElementById('edit-email').value = user.email || '';
            document.getElementById('edit-bio').value = user.bio || '';
        }
        
        // 显示模态框
        editProfileModal.classList.remove('hidden');
        document.body.classList.add('overflow-hidden');
    });
    
    // 关闭编辑资料模态框
    closeModalBtn.addEventListener('click', function() {
        closeEditProfileModal();
    });
    
    // 点击模态框外部关闭
    editProfileModal.addEventListener('click', function(e) {
        if (e.target === this) {
            closeEditProfileModal();
        }
    });
    
    // 表单提交处理
    editProfileForm.addEventListener('submit', function(e) {
        e.preventDefault();
        handleProfileUpdate();
    });
    
    // 邮箱实时验证
    const emailInput = document.getElementById('edit-email');
    if (emailInput) {
        emailInput.addEventListener('input', function() {
            const email = this.value.trim();
            const emailErrorEl = document.getElementById('email-check-message');
            
            if (email && !validateEmail(email)) {
                emailErrorEl.textContent = '请输入有效的邮箱地址';
                emailErrorEl.classList.remove('hidden');
            } else {
                emailErrorEl.classList.add('hidden');
            }
        });
    }
    
    // 取消按钮事件绑定
    const cancelEditBtn = document.getElementById('cancel-edit-btn');
    if (cancelEditBtn) {
        cancelEditBtn.addEventListener('click', function() {
            closeEditProfileModal();
        });
    }
}

/**
 * 关闭编辑资料模态框
 */
export function closeEditProfileModal() {
    const editProfileModal = document.getElementById('edit-profile-modal');
    if (editProfileModal) {
        editProfileModal.classList.add('hidden');
        document.body.classList.remove('overflow-hidden');
    }
}

/**
 * 处理个人资料更新
 */
export function handleProfileUpdate() {
    const user = getUserInfo();
    if (!user) return;
    
    // 获取表单数据
    const username = document.getElementById('edit-username').value.trim();
    const nickname = document.getElementById('edit-user-title').value.trim();
    const email = document.getElementById('edit-email').value.trim();
    const bio = document.getElementById('edit-bio').value.trim();
    
    // 邮箱验证
    if (email && !validateEmail(email)) {
        const emailErrorEl = document.getElementById('email-check-message');
        emailErrorEl.textContent = '请输入有效的邮箱地址';
        emailErrorEl.classList.remove('hidden');
        return;
    }
    
    // 检查邮箱是否已被使用
    checkEmailExists(email, function(emailExists) {
        if (emailExists && email !== user.email) {
            // 邮箱已被使用，显示检查结果模态框
            showEmailCheckModal(true);
            return;
        }
        
        // 更新用户信息
        const updatedUser = {
            ...user,
            username: username,
            nickname: nickname,
            email: email,
            bio: bio
        };
        
        // 保存更新后的用户信息
        setUserInfo(updatedUser);
        
        // 更新页面显示
        updateProfileOnPage(updatedUser);
        
        // 关闭模态框
        closeEditProfileModal();
        
        // 显示成功提示
        showSuccessModal('资料更新成功', '您的个人资料已成功更新！');
    });
}

/**
 * 检查邮箱是否已存在
 * @param {string} email 要检查的邮箱
 * @param {function} callback 回调函数
 */
export function checkEmailExists(email, callback) {
    // 模拟API调用检查邮箱是否存在
    // 在实际项目中，这里应该是一个真实的API请求
    setTimeout(() => {
        // 模拟随机结果，实际项目中应该根据服务器返回判断
        const randomResult = Math.random() > 0.8; // 模拟80%的概率邮箱不存在
        callback(randomResult);
    }, 500);
}

/**
 * 更新页面上的用户资料显示
 * @param {Object} user 更新后的用户信息
 */
export function updateProfileOnPage(user) {
    // 更新个人信息区域
    const profileUserTitle = document.getElementById('profile-user-title');
    if (profileUserTitle) {
        profileUserTitle.textContent = user.nickname || '用户头衔';
    }
    
    const profileUsername = document.getElementById('profile-username');
    if (profileUsername) {
        profileUsername.textContent = user.username || '小镇名称';
    }
    
    // 更新详细资料页面
    const detailUsername = document.getElementById('detail-username');
    if (detailUsername) {
        detailUsername.textContent = user.username || '--';
    }
    
    const detailUserTitle = document.getElementById('detail-user-title');
    if (detailUserTitle) {
        detailUserTitle.textContent = user.nickname || '用户名称';
    }
    
    const detailEmail = document.getElementById('detail-email');
    if (detailEmail) {
        detailEmail.textContent = user.email || '未设置';
    }
    
    const detailBio = document.getElementById('detail-bio');
    if (detailBio) {
        detailBio.textContent = user.bio || '暂无简介';
    }
}